//
//  LiuRefreshControl.swift
//  LiuWeiBo
//
//  Created by 刘晓晨 on 2017/4/2.
//  Copyright © 2017年 刘晓晨. All rights reserved.
//

import UIKit

private let controlHeight:CGFloat = 50

enum refreshType {
    case normal
    case pulling
    case refreshing
}

class LiuRefreshControl: UIControl {

    //懒加载控件
    fileprivate lazy var arrowImageView:UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        return imageView
    }()
    
    fileprivate lazy var refreshImageView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    fileprivate lazy var textLabel:UILabel = {
//        let label = UILabel(fontSize: 12, textColor: UIColor.darkGray, text: "下拉刷新")
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.tintColor = UIColor.darkGray
        label.text = "下来刷新"
        return label
    }()
    
    var  superScrollView:UIScrollView?
    
    var type:refreshType = .normal {
        didSet {
            switch type {
            case .normal:
                //箭头显示,风火轮隐藏,label
                arrowImageView.isHidden = false
                refreshImageView.stopAnimating()
                textLabel.text = "下拉刷新"
                
                //动画
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowImageView.transform = CGAffineTransform.identity
                })
                
                //上一次type是refreshing
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.superScrollView?.contentInset.top -= controlHeight
                    })
                }
            case .pulling:
                //动画,label文字
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
                })
                textLabel.text = "释放加载"
            case .refreshing:
                //箭头隐藏,开启风火轮,label
                arrowImageView.isHidden = true
                refreshImageView.startAnimating()
                textLabel.text = "正在加载..."
                UIView.animate(withDuration: 0.25, animations: {
                    self.superScrollView?.contentInset.top += controlHeight
                }, completion: { (_) in
                    //通知监听者刷新数据
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                        self.sendActions(for: .valueChanged)
                    })
                })
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setupUI() {
        //背景颜色
        backgroundColor = UIColor.groupTableViewBackground
        
        //添加向下的箭头
        addSubview(arrowImageView)
        addSubview(refreshImageView)
        addSubview(textLabel)
        
        //取消系统默认约束
        arrowImageView.translatesAutoresizingMaskIntoConstraints = false
        refreshImageView.translatesAutoresizingMaskIntoConstraints = false
        textLabel.translatesAutoresizingMaskIntoConstraints = false
        
        //约束
        addConstraint(NSLayoutConstraint(item: arrowImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: arrowImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: refreshImageView, attribute: .centerY, relatedBy: .equal, toItem: arrowImageView, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshImageView, attribute: .centerX, relatedBy: .equal, toItem: arrowImageView, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: textLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: textLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 35))
            
    }
    
    //添加到父试图上的时候会执行这个方法
    override func willMove(toSuperview newSuperview: UIView?) {
        
        //判断父试图是否为scrollview
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        //修改view的frame
        self.frame.size = CGSize(width: scrollView.bounds.size.width, height: controlHeight)
        self.frame.origin.y = -controlHeight

        //发送一个KVO监听scrollview的contentOffset属性
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        superScrollView = scrollView
    
    }
    
    //监听消息contentOffset变化会调用这个方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
        //父控件
        let scrollView:UIScrollView = object as! UIScrollView
 
        //滚动的偏移
        let scrollOffsetY = scrollView.contentOffset.y
        
        //计算改变状态的极限条件
        let limtY = -(scrollView.contentInset.top + controlHeight)
        
        //如果是拖拽状态
        if scrollView.isDragging {
            if scrollOffsetY < limtY && type == .normal{
                //变成释放刷新状态
                type = .pulling
            } else if scrollOffsetY >= limtY && type == .pulling {
                //变成下拉刷新状态
                type = .normal
            }
        } else {
            if type == .pulling {
                //变成刷新状态
                type = .refreshing
            }
        }
        
    }
    
    //停止刷新
    func endRefreshing() {
        type = .normal
    }

}
